﻿using AutoMapper;
using D.B.Data.API.Applications.Command.RoleCommand;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Output;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace D.B.Data.API.Applications.CommandHandler.RoleCommandHandler
{
    public class QuerRoleCommandHandler : IRequestHandler<QuerRoleCommand, APIPaging<QueryRoleDTO>>
    {
        private readonly IBaseRepository<RoleModel> _repository;
        private readonly IBaseRepository<UserModel> _Userository;
        private readonly IMapper mapper;

        public QuerRoleCommandHandler(IBaseRepository<RoleModel> repository, IMapper mapper, IBaseRepository<UserModel> userository)
        {
            _repository = repository;
            this.mapper = mapper;
            _Userository = userository;
        }

        public Task<APIPaging<QueryRoleDTO>> Handle(QuerRoleCommand request, CancellationToken cancellationToken)
        {
            var res = _repository.GetAll().AsNoTracking().Where(s => !s.IsDel);

            var model = mapper.Map<List<QueryRoleDTO>>(res);

           foreach (var item in model)
            {
                item.CreateUserName = _Userository.GetAll().AsNoTracking().FirstOrDefault(s => s.Id == item.CreateUserId).UserName;
                if(item.UpDataUserId==null)
                    item.UpdateUserName=string.Empty;
                else 
                    item.UpdateUserName = _Userository.GetAll().AsNoTracking().FirstOrDefault(s => s.Id == item.UpDataUserId).UserName;
            }


            APIPaging<QueryRoleDTO> paging = new APIPaging<QueryRoleDTO>()
            {
                Code = EnumCode.Ok,
                Count = model.Count,
                Msg = "成功",
                PageData = model.OrderByDescending(s => s.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList(),

            };
            return Task.FromResult(paging);

   

        }
    }
}
